<template>
  <el-dialog
    :visible.sync="makeProcessDialog"
    :fullscreen="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false">
    <div style="
      border-bottom: 1px solid rgb(232,232,232);
      position: absolute;
      top: 0; left: 0;
      height: 70px; width: 100%;
      line-height: 70px; padding-left: 20px; padding-right: 20px;">
      <span style="font-weight: bold; font-size: 20px;">流程设计</span>

      <div style="float:right;">
        <el-button type="primary" icon="el-icon-folder-checked" @click="handleSaveBpmn()">保存</el-button>
        <a ref="saveDiagram" class="download"><i class="el-icon-download"></i>下载模型</a>
        <el-button plain icon="el-icon-close" @click="handleClose()"></el-button>
      </div>
    </div>

    <el-row class="module">
      <el-col :span="20"><div class="grid-content bg-purple" id="canvas" ref="canvas" style="height: 870px;"></div></el-col>
      <el-col :span="4"><div class="grid-content bg-purple-light" id="properties"></div></el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import {getBpmnFile, saveBpmn} from "@/api/camunda/bpmn";
import {getProcessBpmn} from '@/api/camunda/camunda'
import CustomModeler from "@/components/CustomModeler";
import {BpmnPropertiesPanelModule, BpmnPropertiesProviderModule, CamundaPlatformPropertiesProviderModule} from "bpmn-js-properties-panel";
import CamundaBpmnModdle from 'camunda-bpmn-moddle/resources/camunda.json'
import MyPropertiesProviderModule from "@/components/PropertiesPanelExtension/provider/MyPropertiesProvider";
import {
  createConditionExpression,
  createExtensionProperties, createLoopCharacteristics,
  createUserTaskExtensionProperties,
  deleteConditionExpression
} from "@/utils/camundaUtils";

export default {
  name: "bpmnMake",
  data() {
    return {
      bpmnId: undefined,
      makeProcessDialog: false,
      bpmnModeler: null,
    }
  },
  methods: {
    init(bpmnId, deploymentId){
      this.bpmnId = bpmnId
      this.makeProcessDialog = true

      if(deploymentId) {
        getProcessBpmn(deploymentId)
          .then(({data}) => {
            this.createBpmn(data)
          }).catch(() => {
            this.makeProcessDialog = false
        })
      } else {
        getBpmnFile(bpmnId)
          .then(({data}) => {
            this.createBpmn(data)
          }).catch(() => {
          this.makeProcessDialog = false
        })
      }

    },
    createBpmn(xml) {
      console.log("________________")
      console.log(this.bpmnModeler)
      if(this.bpmnModeler !== null){
        this.bpmnModeler.destroy()
      }

      this.downloadBPMN(xml)

      // 初始化 BPMN 画布
      this.bpmnModeler = new CustomModeler({
        container: '#canvas',
        propertiesPanel: {
          parent: '#properties'
        },
        additionalModules: [
          BpmnPropertiesPanelModule,
          MyPropertiesProviderModule,
        ],
        moddleExtensions: {
          camunda: CamundaBpmnModdle
        }
      });
      this.bpmnModeler.importXML(xml, (err) => {
        if(err){
          console.log(err)
        }else{
          const eventBus = this.bpmnModeler.get('eventBus')
          const commandStack = this.bpmnModeler.get('commandStack')
          const bpmnFactory = this.bpmnModeler.get('bpmnFactory')
          const eventTypes = ['element.click', 'element.changed'];
          const _this = this

          eventTypes.forEach(function(eventType) {
            eventBus.on(eventType, function (e) {
              if (!e || !e.element) {console.log('无效的e', e); return }
              const element = e.element
              if(e.element.type === 'bpmn:SequenceFlow'){
                console.log(element.businessObject)
                const source = element.businessObject.sourceRef
                if(source && source.$type === 'bpmn:ExclusiveGateway'){
                  createConditionExpression(bpmnFactory, element, commandStack)
                } else {
                  deleteConditionExpression(bpmnFactory, element, commandStack)
                }

                createExtensionProperties(
                  bpmnFactory,
                  element,
                  commandStack,
                  'camunda:ExecutionListener',
                  'task',
                  'com.maxlen.camunda.listener.FlowListener')
              }
              //  && element.businessObject.loopCharacteristics !== undefined
              if (e.element.type === 'bpmn:UserTask') {
                console.log(element.businessObject)
                if(element.businessObject.loopCharacteristics){
                  element.businessObject.assignee = '${assignee}'
                }
                createUserTaskExtensionProperties(bpmnFactory, element, commandStack)
                if(element.businessObject.loopCharacteristics){
                  createLoopCharacteristics(bpmnFactory, element, commandStack)
                }
              }
              if (eventType === 'element.changed') {}
              if (eventType === 'element.click') {}
            })
          })
        }
      });
    },
    handleSaveBpmn() {
      const _this = this
      this.bpmnModeler.saveXML({ format: true }, function(err, xml) {
        const fileContent = new File([xml], 'defaultBpmn.txt', { type: '' })
        const formData = new FormData()
        formData.append('file', fileContent)
        formData.append('bpmnId', _this.bpmnId)
        saveBpmn(formData)
          .then(() => {
            _this.$message({
              message: '保存成功',
              type: 'success',
              duration: 800
            })
          })
          .catch(() => {
            _this.$message({
              message: '保存失败',
              type: 'error',
              duration: 800
            })
          })
      })
    },
    handleClose() {
      if(this.bpmnModeler !== null){
        this.bpmnModeler.destroy()
      }
      this.$emit('init')
      this.makeProcessDialog = false
    },
    downloadBPMN(xml){
      const encodedData = encodeURIComponent(xml)
      const downloadLink = this.$refs.saveDiagram
      downloadLink.href = 'data:application/bpmn-defaultDiagram;charset=UTF-8,' + encodedData
      downloadLink.download = 'diagram.bpmn'
    },
  }
}
</script>

<style scoped>
.module {
  position: absolute;
  top: 70px;
  left: 0;
  width: 100%;
  padding: 0;
}
.download{
  display: inline-block;
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  width: 89px;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin: 10px;
  text-align: center;
}
.download:hover{
  color: #409eff;
  border: 1px solid #409eff;
  cursor: pointer;
}
</style>

